import { createGameRoomManager, createChatRoomManager } from './room-managers.js'

/**
 * 统一的WebSocket连接管理器
 * 自动处理用户信息获取和错误处理
 */
export class UnifiedWebSocketManager {
  constructor() {
    this.connections = new Map() // 存储不同类型的连接
    this.defaultOptions = {
      maxReconnectAttempts: 3,
      reconnectInterval: 3000,
      autoReconnect: true
    }
  }

  /**
   * 获取用户信息（带错误处理）
   */
  getUserInfo() {
    try {
      // 1. 从localStorage获取（最可靠的方式）
      const userId = uni.getStorageSync('userId')
      const userName = uni.getStorageSync('userName')
      const token = uni.getStorageSync('token')

      if (userId && token) {
        console.log('从localStorage获取用户信息:', { userId, userName, token })
        return {
          userId: String(userId),
          userName: userName || '用户' + userId
        }
      }

      // 2. 从userState获取
      const userStateStr = uni.getStorageSync('userState')
      if (userStateStr) {
        try {
          const userState = JSON.parse(userStateStr)
          if (userState.userId && userState.token) {
            console.log('从userState获取用户信息:', userState)
            return {
              userId: String(userState.userId),
              userName: userState.userName || '用户' + userState.userId
            }
          }
        } catch (e) {
          console.warn('解析userState失败:', e)
        }
      }

      // 3. 尝试从Pinia store获取（如果可用）
      try {
        if (typeof uni !== 'undefined' && uni.getStorageSync) {
          const userStore = uni.getStorageSync('userStore')
          if (userStore) {
            try {
              const store = JSON.parse(userStore)
              if (store.userId && store.userName) {
                console.log('从userStore获取用户信息:', store)
                return {
                  userId: String(store.userId),
                  userName: store.userName
                }
              }
            } catch (e) {
              console.warn('解析userStore失败:', e)
            }
          }
        }
      } catch (e) {
        console.warn('获取userStore失败:', e)
      }

      console.error('无法获取用户信息，请先登录')
      console.log('当前存储状态:')
      console.log('userId:', uni.getStorageSync('userId'))
      console.log('userName:', uni.getStorageSync('userName'))
      console.log('token:', uni.getStorageSync('token'))
      console.log('userState:', uni.getStorageSync('userState'))
      return null
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return null
    }
  }

  /**
   * 创建聊天房间连接
   */
  createChatConnection(roomId, options = {}) {
    const userInfo = this.getUserInfo()
    if (!userInfo) {
      console.error('用户信息获取失败，无法创建WebSocket连接')
      return null
    }

    console.log('创建聊天房间连接:', { roomId, userInfo })
    
    const manager = createChatRoomManager(
      roomId, 
      userInfo.userId, 
      userInfo.userName, 
      {
        onOpen: () => {
          console.log('聊天房间连接成功')
          if (options.onOpen) options.onOpen()
        },
        onMessage: (message) => {
          console.log('收到聊天消息:', message)
          if (options.onMessage) options.onMessage(message)
        },
        onClose: (event) => {
          console.log('聊天房间连接关闭:', event)
          if (options.onClose) options.onClose(event)
        },
        onError: (error) => {
          console.error('聊天房间连接错误:', error)
          if (options.onError) options.onError(error)
        },
        onJoin: (message) => {
          console.log('用户加入房间:', message)
          if (options.onJoin) options.onJoin(message)
        },
        onLeave: (message) => {
          console.log('用户离开房间:', message)
          if (options.onLeave) options.onLeave(message)
        },
        onText: (message) => {
          console.log('收到文本消息:', message)
          if (options.onText) options.onText(message)
        },
        onUserListUpdate: (message) => {
          console.log('用户列表更新:', message)
          if (options.onUserListUpdate) options.onUserListUpdate(message)
        },
        onRoomUserCount: (message) => {
          console.log('房间用户数量更新:', message)
          if (options.onRoomUserCount) options.onRoomUserCount(message)
        },
        onSystem: (message) => {
          console.log('系统消息:', message)
          if (options.onSystem) options.onSystem(message)
        },
        onTravel: (message) => {
          console.log('虚拟旅行通知:', message)
          if (options.onTravel) options.onTravel(message)
        },
        onRead: (message) => {
          console.log('已读状态消息:', message)
          if (options.onRead) options.onRead(message)
        }
      }
    )

    // 存储连接
    this.connections.set(`chat_${roomId}`, manager)

    // 新增旅行连接存储示例（后续扩展）
    // this.connections.set(`travel_${friendId}`, manager)
    
    return manager
  }

  /**
   * 创建游戏房间连接
   */
  createGameConnection(gameType, roomId, options = {}) {
    const userInfo = this.getUserInfo()
    if (!userInfo) {
      console.error('用户信息获取失败，无法创建WebSocket连接')
      return null
    }

    console.log('创建游戏房间连接:', { gameType, roomId, userInfo })
    
    const manager = createGameRoomManager(
      gameType,
      roomId,
      userInfo.userId,
      userInfo.userName,
      {
        onOpen: () => {
          console.log('游戏房间连接成功')
          if (options.onOpen) options.onOpen()
        },
        onMessage: (message) => {
          console.log('收到游戏消息:', message)
          if (options.onMessage) options.onMessage(message)
        },
        onClose: (event) => {
          console.log('游戏房间连接关闭:', event)
          if (options.onClose) options.onClose(event)
        },
        onError: (error) => {
          console.error('游戏房间连接错误:', error)
          if (options.onError) options.onError(error)
        },
        onJoin: (message) => {
          console.log('用户加入游戏:', message)
          if (options.onJoin) options.onJoin(message)
        },
        onLeave: (message) => {
          console.log('用户离开游戏:', message)
          if (options.onLeave) options.onLeave(message)
        },
        onReady: (message) => {
          console.log('用户准备状态:', message)
          if (options.onReady) options.onReady(message)
        },
        onGameOp: (message) => {
          console.log('游戏操作:', message)
          if (options.onGameOp) options.onGameOp(message)
        },
        onGameState: (message) => {
          console.log('游戏状态:', message)
          if (options.onGameState) options.onGameState(message)
        },
        onGameStart: (message) => {
          console.log('游戏开始:', message)
          if (options.onGameStart) options.onGameStart(message)
        },
        onGameEnd: (message) => {
          console.log('游戏结束:', message)
          if (options.onGameEnd) options.onGameEnd(message)
        },
        onUserListUpdate: (message) => {
          console.log('游戏用户列表更新:', message)
          if (options.onUserListUpdate) options.onUserListUpdate(message)
        },
        onRoomUserCount: (message) => {
          console.log('游戏房间用户数量:', message)
          if (options.onRoomUserCount) options.onRoomUserCount(message)
        },
        onSystem: (message) => {
          console.log('游戏系统消息:', message)
          if (options.onSystem) options.onSystem(message)
        }
      }
    )

    // 存储连接
    this.connections.set(`game_${gameType}_${roomId}`, manager)
    
    return manager
  }

  /**
   * 关闭指定连接
   */
  closeConnection(key) {
    const manager = this.connections.get(key)
    if (manager) {
      console.log('关闭连接:', key)
      manager.close()
      this.connections.delete(key)
    }
  }

  /**
   * 关闭所有连接
   */
  closeAllConnections() {
    console.log('关闭所有WebSocket连接')
    this.connections.forEach((manager, key) => {
      console.log('关闭连接:', key)
      manager.close()
    })
    this.connections.clear()
  }

  /**
   * 获取连接状态
   */
  getConnectionStatus(key) {
    const manager = this.connections.get(key)
    if (manager) {
      return manager.getConnectionStatus()
    }
    return null
  }

  /**
   * 获取所有连接状态
   */
  getAllConnectionStatus() {
    const status = {}
    this.connections.forEach((manager, key) => {
      status[key] = manager.getConnectionStatus()
    })
    return status
  }
}

// 创建全局实例
export const unifiedWebSocketManager = new UnifiedWebSocketManager()

// 导出便捷函数
export const createChatConnection = (roomId, options) => {
  return unifiedWebSocketManager.createChatConnection(roomId, options)
}

export const createGameConnection = (gameType, roomId, options) => {
  return unifiedWebSocketManager.createGameConnection(gameType, roomId, options)
}

export const closeAllConnections = () => {
  unifiedWebSocketManager.closeAllConnections()
}

export const getConnectionStatus = (key) => {
  return unifiedWebSocketManager.getConnectionStatus(key)
}

export const getAllConnectionStatus = () => {
  return unifiedWebSocketManager.getAllConnectionStatus()
}